import Node from '../core/Node';

export default class Text extends Node{
  static TYPE = {
    STROKE: 1,
    FILL: 2,
  }
  constructor(canvas, style) {
    super(canvas, style);
    this.text = style.text || '';
    this.type = style.type || Text.TYPE.STROKE;
  }

  get width() {
    this.canvas.painter.save();
    this.canvas.painter.font = `${this.size}px ${this.fontFamily}`;
    const width = this.canvas.painter.measureText(this.text).width;
    this.canvas.painter.restore();
    return width;
  }

  get height() {
    return this.size;
  }

  containsPoint(point) {
    let left = this.left;
    if (this.textAlign === 'center') {
      left = this.left - this.width / 2;
    } else if (this.textAlign === 'right') {
      left = this.left - this.width;
    }
    return point.x >= left
      && point.x <= left + this.width
      && point.y >= this.bottom
      && point.y <= this.bottom + parseInt(this.size);
  }

  draw(painter) {
    painter.font = `${this.size}px ${this.fontFamily}`;
    if (this.type === Text.TYPE.FILL) {
      painter.fillStyle = this.color;
      painter.fillText(this.text, this.left / this.scaleX, this.bottom / this.scaleY);
    } else {
      painter.strokeStyle = this.color;
      painter.strokeText(this.text, this.left / this.scaleX, this.bottom / this.scaleY);
    }
  }
}
